class soltObserver {
  observerList = []
  observerInst = null

  constructor(options, targetList, changeValue) {
    this.createInstance(options, targetList, changeValue)
  }

  createInstance(options, targetList, changeValue) {
    try {
      if ('IntersectionObserver' in window) {
        const observer = new IntersectionObserver((...rest) => this.onCallbackFunction(...rest, changeValue), options);
        targetList?.forEach(meter => {
          if (meter) observer?.observe(document.querySelector(`#chart_${meter}`))
        })
        this.observerInst = observer;
      }
    } catch {
      console.error('目前浏览器不支持 IntersectionObserver, 建议替换最新 Coogle Chrome')
    }
  }

  onCallbackFunction(entries, observe, changeValue) {
    const handleList = [...this.observerList];
    entries?.forEach(entry => {
      const findIndex = handleList?.findIndex(it => it?.targetId === entry?.target?.id);
      const handleParam = {
        targetId: entry?.target?.id,
        isIntersecting: entry?.isIntersecting,
      }
      if (entry?.isIntersecting) {
        this.observerInst?.unobserve(entry?.target);
      }
      if (findIndex >= 0) {
        handleList[findIndex] = handleParam;
      } else {
        handleList.push(handleParam)
      }
    })
    changeValue(handleList);
    this.observerList = handleList;
  }

  listenObject(element) {
    this.observerInst?.observe(element)
  }

  clearListenObject(element) {
    this.observerInst?.unobserve(element)
  }

  clearAllListen() {
    this.observerInst?.disconnect()
  }

  clearInstance() {
    if (this.observerInst) this.observerInst = null;
  }

  getSlotInfo() {
    return this.observerList;
  }
}

export default soltObserver